<template>
    <div class="login-container">
        <div class="login-box">
            <h2>智慧会议管理平台</h2>
            <el-tabs v-model="activeTab" class="login-tabs">
                <el-tab-pane label="帐户密码登录" name="account">
                    <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" label-width="auto">
                        <el-form-item prop="phone">
                            <el-input v-model="loginForm.phone" placeholder="请输入手机号" prefix-icon="User" clearable />
                        </el-form-item>

                        <el-form-item prop="pwd">
                            <el-input v-model="loginForm.pwd" type="password" placeholder="请输入密码" show-password
                                prefix-icon="Lock" />
                        </el-form-item>

                        <el-form-item>
                            <el-checkbox v-model="rememberMe">自动登录</el-checkbox>
                            <el-link type="primary" style="float: right;" @click="onForgotPwd">忘记密码</el-link>
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" @click="submitForm" style="width: 100%;">
                                登录
                            </el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>

                <el-tab-pane label="手机登录" name="mobile">
                    <el-form ref="mobileFormRef" :model="mobileForm" :rules="mobileRules" label-width="auto">
                        <el-form-item prop="phone">
                            <el-input v-model="mobileForm.phone" placeholder="请输入手机号" prefix-icon="Phone" clearable />
                        </el-form-item>

                        <el-form-item prop="verifyCode" class="verify-code-item">
                            <template v-if="!showCaptcha">
                                <el-button type="primary" @click="handleShowCaptcha" class="verify-code-btn"
                                    style="width: 120px;">
                                    获取验证码
                                </el-button>
                            </template>
                            <template v-else>
                                <div style="display: flex; align-items: center;">
                                    <canvas ref="verifyCanvas" width="120" height="40" @click="generateVerifyCode"
                                        style="cursor:pointer; border-radius:6px; background:#fff; border:1px solid #eee;"></canvas>
                                    <el-input v-model="mobileForm.verifyCode" placeholder="请输入验证码"
                                        style="width: 120px; margin-left: 10px;" />
                                </div>
                            </template>
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" @click="submitMobileForm" style="width: 100%;">
                                登录
                            </el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>

            <div class="login-footer">
                <span>没有账号？</span>
                <el-link type="primary">注册账户</el-link>
            </div>
        </div>

        <el-dialog v-model="forgotDialogVisible" title="找回密码" width="350px" :close-on-click-modal="false">
            <div style="margin-bottom: 16px;">
                <el-input v-model="forgotForm.phone" placeholder="请输入手机号" clearable style="margin-bottom: 12px;" />
                <el-input v-model="forgotForm.email" placeholder="请输入邮箱" clearable />
            </div>
            <template #footer>
                <el-button @click="forgotDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleForgotSubmit">发送重置</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const router = useRouter()
const activeTab = ref('account')
const rememberMe = ref(false)

// 验证码相关状态
const verifyCodeImage = ref('')
const verifyCodeText = ref('')
const verifyCodeInput = ref('')
const verifyCodeDisabled = ref(false)
const verifyCodeCountdown = ref(0)
const showVerifyCode = ref(false)
const lastVerifyCode = ref('')
const lastVerifyCodeHtml = ref('')

const colorList = [
    '#ff4d4f', // 红
    '#40a9ff', // 蓝
    '#36cfc9', // 青
    '#73d13d', // 绿
    '#faad14', // 黄
    '#9254de', // 紫
    '#ff85c0', // 粉
    '#ffec3d', // 橙
]

let animationFrameId: number | null = null

const loginFormRef = ref()
const loginForm = reactive({
    phone: '',
    pwd: ''
})

const mobileFormRef = ref()
const mobileForm = reactive({
    phone: '',
    verifyCode: ''
})

const loginRules = {
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    pwd: [
        { required: true, message: '请输入密码', trigger: 'blur' },

    ]
}

const mobileRules = {
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    verifyCode: [
        { required: true, message: '请输入验证码', trigger: 'blur' }
    ]
}

const submitForm = async () => {
    const valid = await loginFormRef.value.validate()
    if (valid) {
        try {
            const res = await axios.get("http://localhost:5161/api/Login/Login", {
                params: {
                    phone: loginForm.phone,
                    pwd: loginForm.pwd
                }
            })

            switch (res.data.code) {
                case -1:
                    ElMessage.error("用户名错误")
                    break
                case -2:
                    ElMessage.error("密码错误")
                    break
                case 0:
                    if (rememberMe.value) {
                        localStorage.setItem('rememberedPhone', loginForm.phone)
                        localStorage.setItem('rememberedPwd', loginForm.pwd)
                    } else {
                        localStorage.removeItem('rememberedPhone')
                        localStorage.removeItem('rememberedPwd')
                    }
                    if (res.data.data.token) {
                        sessionStorage.setItem('token', res.data.data.token)
                        axios.defaults.headers.common['Authorization'] = `Bearer` + sessionStorage.getItem("token");
                    }

                    ElMessage.success("登录成功")
                    router.push('/frame')
                    break
                default:
                    ElMessage.error("未知错误")
            }
        } catch (error) {
            ElMessage.error("登录失败，请检查网络")
        }
    }
}

const verifyCanvas = ref<HTMLCanvasElement | null>(null)

const generateVerifyCode = () => {
    const canvas = verifyCanvas.value
    if (!canvas) return
    const ctx = canvas.getContext('2d')!

    // 生成随机验证码
    const characters = '0123456789'
    let code = ''
    for (let i = 0; i < 4; i++) {
        const char = characters.charAt(Math.floor(Math.random() * characters.length))
        code += char
    }
    verifyCodeText.value = code

    // 动画绘制
    let tick = 0
    function draw() {
        if (!canvas) return
        ctx.clearRect(0, 0, canvas.width, canvas.height)
        ctx.fillStyle = '#fff'
        ctx.fillRect(0, 0, canvas.width, canvas.height)

        // 干扰线
        for (let i = 0; i < 5; i++) {
            ctx.strokeStyle = colorList[i % colorList.length]
            ctx.beginPath()
            ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height)
            ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height)
            ctx.stroke()
        }

        // 干扰圆
        for (let i = 0; i < 3; i++) {
            ctx.strokeStyle = colorList[(i + 3) % colorList.length]
            ctx.beginPath()
            ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, 8 + Math.random() * 6, 0, 2 * Math.PI)
            ctx.stroke()
        }

        // 验证码数字
        ctx.font = 'bold 28px Arial'
        ctx.textBaseline = 'middle'
        for (let i = 0; i < code.length; i++) {
            ctx.save()
            ctx.fillStyle = colorList[i % colorList.length]
            // 抖动动画
            const yOffset = Math.sin(tick / 8 + i) * 4
            ctx.translate(20 + i * 25, canvas.height / 2 + yOffset)
            ctx.fillText(code[i], 0, 0)
            ctx.restore()
        }

        tick++
        animationFrameId = requestAnimationFrame(draw)
    }

    if (animationFrameId) cancelAnimationFrame(animationFrameId)
    draw()

    // 转换为图片（如果你需要图片base64，可以加上这句）
    // verifyCodeImage.value = canvas.toDataURL()
}

// 生成随机验证码
const generateMobileVerifyCode = () => {
    // 生成6位随机数字验证码
    return Math.floor(100000 + Math.random() * 900000).toString()
}

// 发送手机验证码
const sendVerifyCode = () => {
    if (!mobileForm.phone) {
        ElMessage.error('请先输入手机号')
        return
    }

    // 检查手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(mobileForm.phone)) {
        ElMessage.error('请输入正确的手机号')
        return
    }

    // 本地模拟发送验证码
    try {
        const verifyCode = generateMobileVerifyCode()
        lastVerifyCode.value = verifyCode
        showVerifyCode.value = true

        // 生成彩色验证码HTML
        let html = '<span class="verify-code-bg">';
        for (let i = 0; i < verifyCode.length; i++) {
            const color = colorList[i % colorList.length];
            html += `<span class="verify-code-char" style="color:${color};font-weight:bold;font-size:18px;display:inline-block;">${verifyCode[i]}</span>`;
        }
        html += '</span>';
        lastVerifyCodeHtml.value = html;

        // 现在我们将验证码存储在本地存储中，模拟发送过程
        localStorage.setItem(`verifyCode_${mobileForm.phone}`, verifyCode)

        // 开始倒计时
        verifyCodeDisabled.value = true
        verifyCodeCountdown.value = 60

        const timer = setInterval(() => {
            verifyCodeCountdown.value--
            if (verifyCodeCountdown.value <= 0) {
                clearInterval(timer)
                verifyCodeDisabled.value = false
                showVerifyCode.value = false // 倒计时结束后隐藏验证码
            }
        }, 1000)

        ElMessage.success('验证码已发送，请注意查收')
        ElMessageBox.alert(`本次验证码为：${verifyCode}`, '调试用验证码', { confirmButtonText: '确定' })
    } catch (error) {
        console.error('发送验证码时发生错误:', error)
        ElMessage.error('发送验证码失败，请稍后重试')
    }
}

// 校验手机验证码
const submitMobileForm = async () => {
    const valid = await mobileFormRef.value.validate()
    if (valid) {
        if (!showCaptcha.value) {
            ElMessage.error('请先获取验证码')
            return
        }
        if (mobileForm.verifyCode.trim().toLowerCase() !== verifyCodeText.value.trim().toLowerCase()) {
            ElMessage.error('验证码错误，请重新输入')
            generateVerifyCode()
            mobileForm.verifyCode = ''
            return
        }
        // 通过校验，执行后续登录逻辑
        ElMessage.success('登录成功')
        router.push('/frame')
    }
}

// 组件挂载时生成验证码
onMounted(() => {
    generateVerifyCode()
    // 自动填充
    const phone = localStorage.getItem('rememberedPhone')
    const pwd = localStorage.getItem('rememberedPwd')
    if (phone && pwd) {
        loginForm.phone = phone
        loginForm.pwd = pwd
        rememberMe.value = true
    }
})

const forgotDialogVisible = ref(false)
const forgotForm = ref({
    phone: '',
    email: ''
})

const onForgotPwd = () => {
    forgotDialogVisible.value = true
}

const handleForgotSubmit = () => {
    // 这里可以做表单校验和接口请求
    if (!forgotForm.value.phone && !forgotForm.value.email) {
        ElMessage.warning('请输入手机号或邮箱')
        return
    }
    // 假设发送成功
    ElMessage.success('重置链接/验证码已发送，请查收！')
    forgotDialogVisible.value = false
    // 清空表单
    forgotForm.value = { phone: '', email: '' }
}

onUnmounted(() => {
    if (animationFrameId) cancelAnimationFrame(animationFrameId)
})

const showCaptcha = ref(false) // 控制验证码区域显示
const inputCaptcha = ref('')   // 用户输入的验证码

const handleShowCaptcha = () => {
    if (!mobileForm.phone) {
        ElMessage.error('请先输入手机号')
        return
    }
    // 你可以加手机号格式校验
    showCaptcha.value = true
    generateVerifyCode()
}
</script>

<style scoped>
.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-image: url('@/assets/images/16.png');
    background-size: cover;
    background-position: center;
}

.login-box {
    width: 400px;
    padding: 30px;
    background: rgba(255, 255, 255, 0.8);
    /* 半透明白色 */
    border-radius: 10px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.login-box h2 {
    text-align: center;
    margin-bottom: 20px;
    color: #333;
}

.login-footer {
    text-align: center;
    margin-top: 20px;
}

.el-input {
    height: 40px;
}

.verify-code-item {
    position: relative;
}

.verify-code-image {
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
    cursor: pointer;
}

.verify-code-btn {
    margin-left: 10px;
}

.verify-code-bg {
    background: #fff;
    border-radius: 8px;
    padding: 4px 16px;
    display: inline-block;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.10);
    min-width: 90px;
}

.verify-code-char {
    animation: bounce 0.7s cubic-bezier(.68, -0.55, .27, 1.55) both;
    margin: 0 3px;
    display: inline-block;
    will-change: transform, opacity;
}

.verify-code-char:nth-child(1) {
    animation-delay: 0s;
}

.verify-code-char:nth-child(2) {
    animation-delay: 0.08s;
}

.verify-code-char:nth-child(3) {
    animation-delay: 0.16s;
}

.verify-code-char:nth-child(4) {
    animation-delay: 0.24s;
}

.verify-code-char:nth-child(5) {
    animation-delay: 0.32s;
}

.verify-code-char:nth-child(6) {
    animation-delay: 0.40s;
}

@keyframes bounce {
    0% {
        transform: scale(0.3) translateY(0);
        opacity: 0.1;
    }

    50% {
        transform: scale(1.3) translateY(-18px);
        opacity: 1;
    }

    100% {
        transform: scale(1) translateY(0);
        opacity: 1;
    }
}

.el-dialog__body {
    padding-bottom: 0 !important;
}
</style>